//    Copyright (C) Kherty.  All rights reserved.
using System;
using System.Globalization;
using OpenLS.Core.Serialization;

namespace OpenLS.Chart
{
    public class NumericValue : ValueBase
    {
        private NumericReference _parent;
        private double _value;
        private string _formatCode;

        public NumericValue(NumericReference parent)
        {
            _parent = parent;
        }

        public NumericValue(NumericReference parent, int index, double value)
            : this(parent)
        {
            Index = index;
            Value = value;
        }
        public NumericValue(int index, double value): this (null, index, value)
        {
        }

        public NumericReference Parent
        {
            get { return _parent; }
            set { _parent = value; }
        }


        public string FormatCode
        {
            get { return _formatCode; }
            set { _formatCode = value;notifyPropertyChanged("FormatCode"); }
        }

        public double Value
        {
            get { return _value; }
            set
            {
                _value = value;
                notifyPropertyChanged("Value");
                if (Parent == null)
                    return; //\\;
                Parent.OnValueChanged();
            }
        }

        internal override void ReadXmlCore(ReadContext context)
        {
            using (var c = context.Read("pt"))
            {
                Index = c.GetInteger("idx");
                string s = c.ReadElementString("v");
                Value = s == NotANumber ? double.NaN : double.Parse(s, CultureInfo.InvariantCulture);
                FormatCode = c.ReadOptionalElementString("formatCode");
            }
        }

        private const string NotANumber = "#N/A";

        internal override void WriteXmlCore(WriteContext context)
        {
            using (WriteContext c = context.Write("pt"))
            {
                c.SetInteger("idx", Index);
                if (double.IsNaN(Value))
                    c.WriteElementString("v", NotANumber);
                else
                    c.WriteElementString("v", string.Format(CultureInfo.InvariantCulture, "{0}", Value));
                c.WriteOptionalElementString("formatCode", FormatCode);
            }
        }
    }
}